#!/usr/bin/env python3

import csv
import logging
import os
import glob


logging.basicConfig()
logger = logging.getLogger("rebuild-jekyll-boards")
logger.setLevel(logging.DEBUG)


BOARD_TEMPLATE = """\
---
layout: board
title: {board_name} SD card images
description: "Minimal, pure and up-to-date vanilla Debian/Ubuntu \
{debian_architecture} SD card images for {board_name} by {board_maker}, SoC: \
{chip_maker} {chip_name}, CPU ISA: {cpu_architecture}"
board_id: {board_id}
board_dtb_name: {device_tree}
board_name: {board_name}
board_maker_name: {board_maker}
board_soc_name: {chip_maker} {chip_name}
board_cpu_name: {cpu} ({cpu_architecture})
board_cpu_arch_isa: {cpu_architecture}
board_cpu_arch_debian: {debian_architecture}
---
"""

DEBIAN_TEMPLATE = """\
---
os: {os}
dist: {dist}
arch: {arch}
name: {name}
exp: {exp}
---
"""


def norm(d):
    return {k.lower().replace(" ", "_"): v for k, v in d.items()}


def read_boards():
    logger.debug("Reading boards...")
    with open("boards.csv") as csvfile:
        return {row["Board ID"]: norm(row) for row in csv.DictReader(csvfile)}


def read_chips():
    logger.debug("Reading chips...")
    with open("chips.csv") as csvfile:
        return {row["Chip ID"]: norm(row) for row in csv.DictReader(csvfile)}


def read_debians():
    logger.debug("Reading debians...")
    with open("debians-arm.csv") as csvfile:
        def key(row):
            return "-".join((row["OS"], row["Dist"], row["Arch"]))
        return {key(row): norm(row) for row in csv.DictReader(csvfile)}


def write_boards(boards, chips):
    for x in glob.glob("docs/_boards/*.md"):
        os.remove(x)
    logger.info("Removed boards")

    for k, board in boards.items():
        board.update(chips[board["chip_id"]])
        if board["debian_architecture"] not in ("armhf", "arm64", ):
            continue
        with open(f"docs/_boards/{k}.md", "w") as boardf:
            boardf.write(BOARD_TEMPLATE.format(**board))
    logger.info("Wrote %d boards", len(boards))


def write_debians(debians):
    for x in glob.glob("docs/_debians/*.md"):
        os.remove(x)
    logger.info("Removed debians")

    for i, (k, debian) in enumerate(debians.items()):
        with open(f"docs/_debians/{i:02}-{k}.md", "w") as debiansf:
            debiansf.write(DEBIAN_TEMPLATE.format(**debian))
    logger.info("Wrote %d debians", len(debians))


if __name__ == "__main__":
    write_boards(read_boards(), read_chips())
    write_debians(read_debians())
